package cn.stronglink.esm27.collection.iot.devices.esm27.response.handle;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.stronglink.esm27.collection.core.message.IMessageHandle;
import cn.stronglink.esm27.collection.core.util.ByteUtil;
import cn.stronglink.esm27.collection.core.util.ContextUtils;
import cn.stronglink.esm27.collection.iot.devices.esm27.message.ESM27MessageTools;
import cn.stronglink.esm27.collection.iot.devices.esm27.message.MQMessageOfESM27;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.AlarmOptionEntity;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.DeviceOptionEntity;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.ESM27ResponseMessageEntity;
import cn.stronglink.esm27.collection.mq.TopicSender;
import io.netty.channel.ChannelHandlerContext;

/**
 * 获取设备设置数据的反馈
 * @author yuzhantao
 *
 */
public class GetDeviceOptionReturnHandle implements IMessageHandle<ESM27ResponseMessageEntity, Object> {
	private final static String ACTION_CODE="GetDeviceOptionReturn";
	private final static String TOPIC_NAME="ESM27ToService";		// MQ发送主题
	private final static Logger logger = LogManager.getLogger(GetDeviceOptionReturnHandle.class.getName());
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	
	@Override
	public boolean isHandle(ESM27ResponseMessageEntity t) {
		if(t.getCommandCode()==0x03) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, ESM27ResponseMessageEntity t) {
		DeviceOptionEntity option = new DeviceOptionEntity();
		// 设置传感器数量
		option.setSensorCount(ByteUtil.byteToUInt(t.getDatas()[0]));
		// 设置设备地址
		option.setDeviceAddress(t.getDatas()[1]);
		// 设备设备使能标志
		short deviceUseData = ByteUtil.byteArrToShort(t.getDatas(), 2);
		option.setDeviceUses(ESM27MessageTools.getSensorUseList(deviceUseData));
		// 设置无线通信信道
		option.setWirelessCommunicationChannel(ByteUtil.byteToUInt(t.getDatas()[4]));
		// 设置无线通信速率
		option.setWirelessCommunicationRate(ByteUtil.byteToUInt(t.getDatas()[5]));
		// 设置北斗刷新周期
		option.setBeidouRefreshCycle(ByteUtil.byteArrToShort(t.getDatas(), 6));
		// 设置报警使能
		option.setAlarmOptions(getAlarmOptionList(ByteUtil.bytesToInt(t.getDatas(), 8)));
		
		// 设置电池欠压阀值
		option.setBatteryUndervoltageThreshold(ByteUtil.bytesToFloat(t.getDatas(), 12));
		// 设置电池欠压关机阀值
		option.setBatteryUndervoltageShutdownThreshold(ByteUtil.bytesToFloat(t.getDatas(), 16));
		// 设置背光延时时间
		option.setBacklightDelayTime(ByteUtil.byteToUInt(t.getDatas()[20]));
		// 设置背光模式
		option.setBacklightMode(ByteUtil.byteToUInt(t.getDatas()[21]));
		// 设置泵周期
		option.setPumpCycle(ByteUtil.byteToUInt(t.getDatas()[22]));
		// 设置泵占空比
		option.setPumpDutyRatio(ByteUtil.byteToUInt(t.getDatas()[23]));
		// 设置系统时间
		GregorianCalendar gc = new GregorianCalendar();
		gc.set(Calendar.YEAR,2000+t.getDatas()[24]);	//设置年
		gc.set(Calendar.MONTH, t.getDatas()[25]);		//这里0是1月..以此向后推
		gc.set(Calendar.DAY_OF_MONTH, t.getDatas()[26]);//设置天
		gc.set(Calendar.HOUR_OF_DAY, t.getDatas()[27]);	//设置小时
		gc.set(Calendar.MINUTE, t.getDatas()[28]);		//设置分
		gc.set(Calendar.SECOND, t.getDatas()[29]);		//设置秒
		option.setCurrentTime(gc.getTimeInMillis());
		
		MQMessageOfESM27 message = new MQMessageOfESM27();
		message.setActioncode(ACTION_CODE);
		message.setTimeStamp(System.currentTimeMillis());
		message.setAwsPostdata(option);
		message.setIsSuccess(true);
		
		String json = JSON.toJSONString(message);
		topicSender.send(TOPIC_NAME, json);
		logger.info("发送[{}]到MQ完成:{}","获取设备设置参数的反馈信息",json);
		
		return null;
	}

	/**
	 * 根据协议获取报警设置
	 * @param srcData
	 * @return
	 */
	private List<AlarmOptionEntity> getAlarmOptionList(int srcData){
		List<AlarmOptionEntity> ret = new ArrayList<AlarmOptionEntity>();
		// 数据源的前28位代表7个传感器的4种报警设置
		for(int i=0;i<28;i++) {
			AlarmOptionEntity alarmOpt = new AlarmOptionEntity();
			int sensorNumber = i/4+1;
			alarmOpt.setSensorChannelNumber(sensorNumber);
			alarmOpt.setSensorName("传感器"+sensorNumber);
			switch(i%4) {
			case 0:
				alarmOpt.setAlarmContent("AL报警");
				break;
			case 1:
				alarmOpt.setAlarmContent("AH报警");
				break;
			case 2:
				alarmOpt.setAlarmContent("STEL报警");
				break;
			case 3:
				alarmOpt.setAlarmContent("TWA报警");
				break;
			}
			alarmOpt.setEnable(true);
			ret.add(alarmOpt);
		}
		// 电池报警设置
		AlarmOptionEntity batteryAlarmOpt = new AlarmOptionEntity();
		batteryAlarmOpt.setSensorName("电池");
		batteryAlarmOpt.setAlarmContent("欠压报警");
		batteryAlarmOpt.setEnable(isIntNumberNBitONEInBinary(srcData,28));
		ret.add(batteryAlarmOpt);
		// 泵报警设置
		AlarmOptionEntity pumpAlarmOpt = new AlarmOptionEntity();
		pumpAlarmOpt.setSensorName("泵");
		pumpAlarmOpt.setAlarmContent("堵报警");
		pumpAlarmOpt.setEnable(isIntNumberNBitONEInBinary(srcData,29));
		ret.add(pumpAlarmOpt);
		// 北斗报警设置
		AlarmOptionEntity beidouAlarmOpt = new AlarmOptionEntity();
		beidouAlarmOpt.setSensorName("北斗");
		beidouAlarmOpt.setAlarmContent("信号异常报警");
		beidouAlarmOpt.setEnable(isIntNumberNBitONEInBinary(srcData,30));
		ret.add(beidouAlarmOpt);
		// 无线报警设置
		AlarmOptionEntity wirelessAlarmOpt = new AlarmOptionEntity();
		wirelessAlarmOpt.setSensorName("无线");
		wirelessAlarmOpt.setAlarmContent("接入异常报警");
		wirelessAlarmOpt.setEnable(isIntNumberNBitONEInBinary(srcData,31));
		ret.add(wirelessAlarmOpt);
		
		return ret;
	}
	
	/**
	 * 判断指定int数值的某位是否为1
	 * @param number
	 * @param nbit
	 * @return
	 */
	private boolean isIntNumberNBitONEInBinary(int number,int nbit){  
		StringBuffer sb = new StringBuffer();
		sb.append(Integer.toBinaryString(number));
		while(sb.length()<32) {
			sb.insert(0, "0");
		}
		return sb.toString().substring(nbit, nbit+1).equals("1");
	}
}

